import {
  RequestDataTypeEnum,
  RequestDatasetEnum,
  RequestSectionEnum,
  ResponseFormatterEnum,
  ResponseSectionEnum,
  type Auth,
  type Body,
  type KeyValueChecked,
  FormDataTypeEnum,
  type StatePartial,
  type MockItem,
} from "@sparrow/common/types/workspace/http-request-mock-tab";
import {
  TabTypeEnum,
  type Tab,
  type Path,
  TabPersistenceTypeEnum,
} from "@sparrow/common/types/workspace/tab";
import { v4 as uuidv4 } from "uuid";
import {
  HttpRequestMockAuthModeBaseEnum,
  HttpRequestMockMethodBaseEnum,
} from "../types/workspace/http-request-mock-base";
import { CollectionRequestAddToBaseEnum } from "../types/workspace/collection-base";

export class InitMockRequestTab {
  private _tab: Tab;
  /**
   *
   * @param _id - Request mongo id
   * @param _workspaceId - Workspace Id to which Request belongs to
   */
  constructor(_id: string, _workspaceId: string) {
    this._tab = {
      id: _id,
      tabId: uuidv4(),
      name: "New Mock REST API",
      type: TabTypeEnum.MOCK_REQUEST,
      persistence: TabPersistenceTypeEnum.PERMANENT,
      description: "[]",
      source: "USER",
      isDeleted: false,
      activeSync: false,
      label: "",
      property: {
        mockRequest: {
          method: HttpRequestMockMethodBaseEnum.GET,
          body: {
            raw: "",
            urlencoded: [
              {
                key: "",
                value: "",
                checked: false,
              },
            ],
            formdata: [
              {
                key: "",
                value: "",
                base: "",
                checked: false,
                type: FormDataTypeEnum.TEXT,
              },
            ],
          },
          url: "",
          responseBody: "",
          headers: [
            {
              key: "",
              value: "",
              checked: false,
            },
          ],
          responseHeaders: [
            {
              key: "",
              value: "",
              checked: false,
            },
          ],
          queryParams: [
            {
              key: "",
              value: "",
              checked: false,
            },
          ],
          responseStatus: "",
          responseDate: "",
          autoGeneratedHeaders: [
            {
              key: "Accept",
              value: "*/*",
              checked: true,
            },
            {
              key: "Connection",
              value: "keep-alive",
              checked: true,
            },
            {
              key: "User-Agent",
              value: "SparrowAgent/v2",
              checked: true,
            },
            {
              key: "Accept-Encoding",
              value: "gzip, deflate, br",
              checked: true,
            },
          ],
          items: [],
          state: {
            requestBodyLanguage: RequestDataTypeEnum.TEXT,
            requestBodyNavigation: RequestDatasetEnum.NONE,
            requestAuthNavigation: HttpRequestMockAuthModeBaseEnum.NO_AUTH,
            requestNavigation: RequestSectionEnum.PARAMETERS,
            responseNavigation: ResponseSectionEnum.RESPONSE,
            responseBodyLanguage: RequestDataTypeEnum.TEXT,
            responseBodyFormatter: ResponseFormatterEnum.PRETTY,
            requestExtensionNavigation: "",
            requestLeftSplitterWidthPercentage: 50,
            requestRightSplitterWidthPercentage: 50,
            isExposeEditDescription: true,
            isSendRequestInProgress: false,
            isSaveDescriptionInProgress: false,
            isSaveRequestInProgress: false,
            isParameterBulkEditActive: false,
            isHeaderBulkEditActive: false,
            isChatbotActive: false,
            isChatbotSuggestionsActive: true,
            isChatbotGeneratingResponse: false,
            isDocGenerating: false,
            isDocAlreadyGenerated: false,
          },
          auth: {
            bearerToken: "",
            basicAuth: {
              username: "",
              password: "",
            },
            apiKey: {
              authKey: "",
              authValue: "",
              addTo: CollectionRequestAddToBaseEnum.HEADER,
            },
          },
          ai: {
            prompt: "",
            conversations: [],
            threadId: "",
          },
        },
      },
      path: {
        workspaceId: _workspaceId,
        collectionId: "",
        folderId: "",
        requestId: "",
      },
      isSaved: true,
      index: 0,
      isActive: true,
      timestamp: new Date().toString(),
    };
    if (!_id || !_workspaceId) {
      console.error("invalid id or workspace id on create new tab request!");
    }
  }
  public getValue(): Tab {
    return this._tab;
  }
  public updateId(_id: string) {
    this._tab.id = _id;
  }
  public updateName(_name: string) {
    this._tab.name = _name;
  }
  public updateDescription(_description: string) {
    this._tab.description = _description;
  }
  public updatePath(_path: Path) {
    this._tab.path = _path;
  }
  public updateUrl(_url: string) {
    if (_url && this._tab.property.mockRequest) {
      this._tab.property.mockRequest.url = _url;
    }
  }
  public updateMethod(_method: HttpRequestMockMethodBaseEnum) {
    if (_method && this._tab.property.mockRequest) {
      this._tab.property.mockRequest.method = _method;
    }
  }
  public updateBody(_body: Body) {
    if (_body && this._tab.property.mockRequest) {
      this._tab.property.mockRequest.body = _body;
    }
  }

  public updateResponseBody(_body: string) {
    if (_body && this._tab.property.mockRequest) {
      this._tab.property.mockRequest.responseBody = _body;
    }
  }
  public updateQueryParams(_queryParams: KeyValueChecked[]) {
    if (_queryParams && this._tab.property.mockRequest) {
      this._tab.property.mockRequest.queryParams = _queryParams;
    }
  }
  public updateHeaders(_headers: KeyValueChecked[]) {
    if (_headers && this._tab.property.mockRequest) {
      this._tab.property.mockRequest.headers = _headers;
    }
  }
  public updateResponseHeaders(_headers: KeyValueChecked[]) {
    if (_headers && this._tab.property.mockRequest) {
      this._tab.property.mockRequest.responseHeaders = _headers;
    }
  }
  public updateResponseStatus(_status: string) {
    if (_status && this._tab.property.mockRequest) {
      this._tab.property.mockRequest.responseStatus = _status;
    }
  }
  public updateResponseDate(_date: string) {
    if (_date && this._tab.property.mockRequest) {
      this._tab.property.mockRequest.responseDate = _date;
    }
  }
  public updateAuth(_auth: Auth) {
    if (_auth && this._tab.property.mockRequest) {
      this._tab.property.mockRequest.auth = _auth;
    }
  }
  public updateAutoGeneratedHeaders(_autoGeneratedHeaders: KeyValueChecked[]) {
    if (this._tab.property.mockRequest) {
      this._tab.property.mockRequest.autoGeneratedHeaders =
        _autoGeneratedHeaders;
    }
  }
  public updateItems(_items: MockItem[]) {
    if (this._tab.property.mockRequest) {
      this._tab.property.mockRequest.items = _items;
    }
  }
  public updateIsSave(_isSave: boolean) {
    this._tab.isSaved = _isSave;
  }
  public updateState(_state: StatePartial) {
    if (this._tab.property.mockRequest) {
      this._tab.property.mockRequest.state = {
        ...this._tab.property.mockRequest.state,
        ..._state,
      };
    }
  }
  public updateChatbotState(_isActive: boolean) {
    if (this._tab.property.mockRequest?.state) {
      this._tab.property.mockRequest.state.isChatbotActive = _isActive;
    }
  }
  public updateLabel(_label: string) {
    this._tab.label = _label;
  }
}
